// pages/goods/goods.js
// const app = getApp()
const db = wx.cloud.database()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    cat:'',
    name:'',
    brief:'',
    price:0.00,
    lowprice:0.00,
    unit:'',
    preimage:[], //产品img的临时地址
    preconimage:[], //详情img的临时地址
    picsUrl:[], //产品img的cloud地址
    conUrl:[], //详情img的cloud地址
    new:true, //新建，修改false
    cloudimgFlag:false //img为云存储地址 true，img为临时地址 false
  },

  //获取类别
  catinput(e){
    this.data.cat = e.detail.value
  },
  //获取品名
  nameBlur(e){
    this.data.name = e.detail.value
  },
  //获取简介
  briefBlur(e){
    this.data.brief = e.detail.value
  },
  //获取原价
  priceinput(e){
    this.data.price = e.detail.value
  },
  //获取折扣价
  lowpriceinput(e){
    this.data.lowprice = e.detail.value
  },
  //获取优品计量单位
  unitinput(e){
    this.data.unit = e.detail.value
  },

  // 建立图片预览数组preimage
  picspre(e){
    var that = this
    if(e.currentTarget.dataset.name=='preimage'){
      wx.chooseMedia({
        count: 9,
        mediaType: ['image','video'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
          let oldpre =that.data.preimage
          let newpre = res.tempFiles
          that.setData({
            preimage: [...oldpre,...res.tempFiles]
          })
          console.log(that.data.preimage)
        }
      })
    }else if(e.currentTarget.dataset.name=='preconimage'){
      wx.chooseMedia({
        count: 9,
        mediaType: ['image','video'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
          let oldpre =that.data.preconimage
          that.setData({
            preconimage: [...oldpre,...res.tempFiles]
          })
          console.log(that.data.preconimage)
        }
      })
    }
  },
  //删除预览图片
  onclose(e){
    var that=this
    if(!that.data.cloudimgFlag){
      if(e.currentTarget.dataset.name=='preimage'){
        this.data.preimage.splice(e.currentTarget.dataset.index,1) //splice返回值是删除的那个数据
        let preimage = this.data.preimage
        this.setData({
          preimage
        })
      }else if(e.currentTarget.dataset.name=='preconimage'){
        this.data.preconimage.splice(e.currentTarget.dataset.index,1) //splice返回值是删除的那个数据
        let preconimage = this.data.preconimage
        this.setData({
          preconimage
        })
      }
    }else{
      if(e.currentTarget.dataset.name=='picsUrl'){
        this.data.picsUrl.splice(e.currentTarget.dataset.index,1) //splice返回值是删除的那个数据
        let picsUrl = this.data.picsUrl
        this.setData({
          picsUrl
        })
      }else if(e.currentTarget.dataset.name=='conUrl'){
        this.data.conUrl.splice(e.currentTarget.dataset.index,1) //splice返回值是删除的那个数据
        let conUrl = this.data.conUrl
        this.setData({
          conUrl
        })
      }
    }
  },
  //图片预览
  preimagefun(e){
    let that = this
    let arr = []
    if(!that.data.cloudimgFlag){
      if(e.currentTarget.dataset.name=='preimage'){
        var imageurl = that.data.preimage
      }else if(e.currentTarget.dataset.name=='preconimage'){
        var imageurl = that.data.preconimage
      }
      arr.push(imageurl[e.currentTarget.dataset.index].tempFilePath)
      wx.previewImage({
        current:e.currentTarget.dataset.index,
        urls: arr,
        success: (res) => {
          console.log('预览成功',res)
        }
      })
    }else{
      if(e.currentTarget.dataset.name=='picsUrl'){
        var imageurl = that.data.picsUrl
      }else if(e.currentTarget.dataset.name=='conUrl'){
        var imageurl = that.data.conUrl
      }
      arr.push(imageurl[e.currentTarget.dataset.index])
      wx.previewImage({
        current:e.currentTarget.dataset.index,
        urls: arr,
        success: (res) => {
          console.log('预览成功',res)
        }
      })
    }
  },
  //将产品图片数组picsUrl和详情图片数组conUrl上传到云存储
  picsToCloud(){
    var that = this
    that.data.picsUrl = []
    that.data.conUrl = []
    if (that.data.preimage.length > 0) {
      for (var i = 0; i < that.data.preimage.length; i++) {
        let filePath = that.data.preimage[i].tempFilePath
        console.log(filePath)
        // console.log(filePath)
        //云函数，进行上传操作	
        wx.cloud.uploadFile({			
          filePath,
          cloudPath: Date.now()+'.jpg',//new Date().getTime()+'.jpg',
          success(res) {
            that.data.picsUrl.push(res.fileID)
            console.log('产品图片上传成功',that.data.picsUrl)
          },
          fail(err){
            console.log('上传不成功',err)
          }
        });
      }
    }
    if (that.data.preconimage.length > 0) {
      for (var i = 0; i < that.data.preconimage.length; i++) {
        let filePath = that.data.preconimage[i].tempFilePath
        //云函数，进行上传操作				
        wx.cloud.uploadFile({
          filePath,
          cloudPath: Date.now()+'.jpg',//new Date().getTime()+'.jpg',
          success(res) {
            that.data.conUrl.push(res.fileID)
            console.log('产品详情上传成功',that.data.conUrl)
          },
        });
      }
    }
  },
  // 添加或者修改goods数据
  addorupdate() {
    var that = this
    if (that.data.new){
      if (that.data.cat == ''){
        wx.showModal({
          title: '温馨提醒',
          content: '请输入品类！',
          showCancel: false
        })
      }
      else if (that.data.name == '') {
        wx.showModal({
          title: '温馨提醒',
          content: '请输入优品名称！',
          showCancel: false
        })
      }
      else if (that.data.brief == '') {
        wx.showModal({
          title: '温馨提醒',
          content: '请输入营业地点',
          showCancel: false
        })
      }
      else if (that.data.brief == '') {
        wx.showModal({
          title: '温馨提醒',
          content: '请输入优品简介',
          showCancel: false
        })
      }
      else if (that.data.price == 0) {
        wx.showModal({
          title: '温馨提醒',
          content: '请输入优品原价',
          showCancel: false
        })
      }
      else if (that.data.lowprice == 0) {
        wx.showModal({
          title: '温馨提醒',
          content: '请输入折扣价',
          showCancel: false
        })
      }
      else if (that.data.unit == '') {
        wx.showModal({
          title: '温馨提醒',
          content: '请输入优品单位',
          showCancel: false
        })
      }
      else if (that.data.preimage == '') {
        wx.showModal({
          title: '温馨提醒',
          content: '请上传优品照片',
          showCancel: false
        })
      }
      else if (that.data.precomimage == '') {
        wx.showModal({
          title: '温馨提醒',
          content: '请上传优品详情',
          showCancel: false
        })
      }
      else{
        db.collection('goods')
        .where({
          name:that.data.name
        })
        .get()
        .then(res=>{
          console.log(res.data.length)
          if(res.data.length == 0){
            console.log(that.data.picsUrl.length)

              db.collection('goods').add({
                data: {
                  block:wx.getStorageSync('block'),
                  cat:that.data.cat,
                  name:that.data.name,
                  brief:that.data.brief,
                  price:that.data.price,
                  lowprice:that.data.lowprice,
                  unit:that.data.unit,
                  imgbrief:that.data.picsUrl,
                  imgcon:that.data.conUrl
                }
              })
              .then(res => {
                wx.showModal({
                  title: '恭喜',
                  content: '优品添加成功！',
                  showCancel: false,
                  complete() {
                    // 跳转到ypba页面
                    wx.redirectTo({
                      url: '/pages/ypba/ypba'
                    })
                  }
                })
              })

          }else{
            wx.showModal({
              title: '提醒',
              content: '优品库已有该商品',
              showCancel: false,
            })
          }
        })

      }
    }
    else{
      db.collection('goods').where({
        name:that.data.name
      }).get({
        success:function(res){
          if(res.data.length == 1 ){
            console.log(res.data[0]._id)
            wx.cloud.callFunction({
              name: 'zpgl_update',
              data: {
                DBname:'goods',
                goodsid: res.data[0]._id,
                cat:that.data.cat,
                name:that.data.name,
                brief:that.data.brief,
                price:that.data.price,
                lowprice:that.data.lowprice,
                unit:that.data.unit,
                imgbrief:that.data.imgbrief,
                imgcon:that.data.imgcon
              }
            }).then(res => {
              console.log('信息修改成功',res)
              wx.showModal({
                title: '恭喜',
                content: '信息修改成功！',
                showCancel: false,
                complete() {
                  // 跳转到ypba页面
                  wx.redirectTo({
                    url: '/pages/ypba/ypba'
                  })
                }
              })
            }).catch(err => {
              console.log(err)
            })
          }else{
            wx.showModal({
              title: '温馨提醒',
              content: '优品备案登记有问题，请联系客服',
              showCancel: false
            })            
          }
        },
        fail:function(){
          console.log("搜素优品失败");
        }
      })
    }
  },
  // 上传
  async sumit(){
    let that = this
    //获取产品、详情图片数组
    await that.picsToCloud()
    setTimeout(function() {
      console.log(that.data.picsUrl.length,that.data.conUrl.length)
      that.addorupdate()
    }, 3000);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this
    if (options.name) { //已有记录
      that.data.new = false
      that.setData({
        cloudimgFlag:true
      })
      db.collection('goods')
      .where({
        name:options.name
      })
      .get({
        success:function(res){
          // console.log(res)
          that.setData({
            cat:res.data[0].cat,
            name:options.name,
            brief:res.data[0].brief,
            price:res.data[0].price,
            lowprice:res.data[0].lowprice,
            unit:res.data[0].unit,
            picsUrl:res.data[0].imgbrief,
            conUrl:res.data[0].imgcon,
          })
        },
        fail:function(err){
          console.log('err',err)
        },
      })
    }else{
      console.log('这次是添加数据')
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})